//
//  QCGradientLayerUtil.m
//  QCAppProject
//
//  Created by yjl on 2021/8/16.
//

#import "QCGradientLayerUtil.h"

@implementation QCGradientLayerUtil

+ (void)configLayerGradientColor:(UIView *)view originColor:(UIColor *)originColor targetColor:(UIColor *)targetColor {
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
//    UIColor *color1= RGB(222, 124, 104);//kHexColor(@"ed7863");
//    UIColor *color2 = RGB(220, 115, 102);//e95c60
    gradientLayer.colors = @[(__bridge id)originColor.CGColor, (__bridge id)targetColor.CGColor];
    gradientLayer.locations = @[@0.5, @1.0];
    gradientLayer.startPoint = CGPointMake(0, 0);
    gradientLayer.endPoint = CGPointMake(0, 1.0);
    if ([view isKindOfClass:[UINavigationBar class]]) {
        NSLog(@"%d---",kTopBarHeight);
        //获取状态栏的rect
        CGRect statusRect = [[UIApplication sharedApplication] statusBarFrame];
        //获取导航栏的rect
        CGRect navRect = view.frame;
        //有些机型statusRect.height = 43,为了适配特殊机型
        CGFloat height = MAX(statusRect.size.height+navRect.size.height, kTopBarHeight);
        gradientLayer.frame = CGRectMake(0, 0, SCREEN_WIDTH, height);
        UIImage *image = [self imageFromLayer:gradientLayer];
        [(UINavigationBar *)view setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
    } else {
        gradientLayer.frame = view.frame;
        [view.layer addSublayer:gradientLayer];
    }
}

+ (UIImage *)imageFromLayer:(CALayer *)layer{
    UIGraphicsBeginImageContextWithOptions(layer.frame.size, NO, 0);
    
    [layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return outputImage;
}


@end
